﻿using AF_Application.App;
using AF_Application.Domain;
using AF_Application.Interface.App;
using AF_Application.Interface.Cache;
using AF_Application.Interface.Domain;
using AF_Application.Interface.Log;
using AF_Application.Interface.Repertory;
using AF_Cache;
using AF_Cache.Session;
using AF_CouchebaseLog;
using AF_DataModel;
using AF_Repertory.Repertories;
using Autofac;
using Autofac.Builder;
using Autofac.Configuration;
using Autofac.Core;
using Autofac.Integration.Web;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;

namespace AF_IOC
{
    public class IOC
    {
        private static readonly object lockObj = new object();
        private ContainerBuilder Builder = null;
        public IContainerProvider Container { get; set; }
        private bool Inited = false;
        private static IOC _Instance = null;
        public static IOC Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (lockObj)
                    {
                        if (_Instance == null)
                        {
                            _Instance = new IOC();
                            _Instance.Init();
                        }
                    }
                }
                return _Instance;
            }
        }

        public void Init()
        {
            if (!Inited)
            {
                Builder = new ContainerBuilder();

                //单例，整个应用（网站）都使用一个对象
                Builder.RegisterType<CouchbaseCacheProvider>()
                  .As<ICacheProvider>().SingleInstance();

                Builder.RegisterType<CouchbaseSessionCacheProvider>()
                    .As<ISessionCacheProvider>().SingleInstance();

                Builder.RegisterType<CouchbaseLogProvider>()
                    .As<ILogProvider>().SingleInstance();


                Builder.RegisterType<DBRepertory>()
                    .As<IDBRepertory>().InstancePerRequest();

                Builder.RegisterType<DefaultDomain>()
                    .As<IDefaultDomain>().InstancePerRequest();

                Builder.RegisterType<AppImpl>()
                    .As<IAppImpl>().InstancePerRequest();

                Container = new ContainerProvider(Builder.Build());
                Inited = true;
            }
        }

        public T Get<T>()
        {
            IContainerProviderAccessor CPA = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
            return CPA.ContainerProvider.RequestLifetime.Resolve<T>();
        }
    }
}
